package com.doge.calcalbum.business.skin

import android.content.ComponentName
import android.content.pm.PackageManager
import com.doge.calcalbum.R
import com.doge.calcalbum.analysis.analysisEvent
import com.doge.calcalbum.analysis.skin_use
import com.doge.calcalbum.utils.appContext
import com.doge.calcalbum.utils.spReadInt
import com.doge.calcalbum.utils.spWrite


data class Skin(
    val id: Int,
    val iconResId: Int,
    val textId: Int,
    val type: String,
) {
    companion object {
        const val TYPE_DEFAULT = "默认"
        const val TYPE_SKIN = "皮肤"
        const val TYPE_FEE = "套装"
    }
}

object SkinHelper {
    private const val spFolder = "skins"
    private const val spKey = "using"
    val usingSkinId: Int get() = spReadInt(spKey, 0, spFolder)
    private fun setUsingSkinId(skinId: Int) = spWrite(spKey, skinId, spFolder)

    val skinList = listOf(
        Skin(0, R.mipmap.skin_bxx, R.string.skin_bxx, Skin.TYPE_DEFAULT),
        Skin(1, R.mipmap.skin_calculator3, R.string.skin_calc_suit, Skin.TYPE_SKIN),
        Skin(2, R.mipmap.skin_calculator1, R.string.skin_calc2, Skin.TYPE_SKIN),
        Skin(3, R.mipmap.skin_calculator2, R.string.skin_calc, Skin.TYPE_SKIN),
        Skin(4, R.mipmap.skin_date, R.string.skin_date, Skin.TYPE_SKIN),
        Skin(5, R.mipmap.skin_internet2, R.string.skin_internet, Skin.TYPE_SKIN),
        Skin(6, R.mipmap.skin_internet1, R.string.skin_internet2, Skin.TYPE_SKIN),
        Skin(7, R.mipmap.skin_music, R.string.skin_music, Skin.TYPE_SKIN),
        Skin(8, R.mipmap.skin_weather, R.string.skin_weather, Skin.TYPE_SKIN),
        Skin(9, R.mipmap.skin_notebook, R.string.skin_note, Skin.TYPE_SKIN),
        Skin(10, R.mipmap.skin_photo, R.string.skin_photo, Skin.TYPE_SKIN),
        Skin(11, R.mipmap.skin_video, R.string.skin_video, Skin.TYPE_SKIN),
    )

    fun setup(skinId: Int?) {
        if (skinId == null) return
        if (usingSkinId == skinId) return
        setUsingSkinId(skinId)
        analysisEvent("${skin_use}_${skinId}")

        val disabled = PackageManager.COMPONENT_ENABLED_STATE_DISABLED
        val enable = PackageManager.COMPONENT_ENABLED_STATE_ENABLED
        repeat(skinList.size) {
            appContext.packageManager.setComponentEnabledSetting(
                ComponentName(appContext, "${appContext.packageName}.Alias$it"),
                if (skinId == it) enable else disabled,
                PackageManager.DONT_KILL_APP
            )
        }

    }
}